package com.caojm.mptools.client.commands;

import com.caojm.mptools.client.PermissionManager;
import com.caojm.mptools.client.utils.LoggerUtil;  // 引入日志工具类
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.Text;

import com.mojang.brigadier.arguments.StringArgumentType;


public class GrantCommand {

    private static PermissionManager permissionManager = new PermissionManager();

    public static void register() {
        CommandManager.literal("mp")
                .then(CommandManager.literal("grant")  // 'grant' 命令
                        .then(CommandManager.argument("player", StringArgumentType.string())  // 玩家名字
                                .then(CommandManager.argument("permission", StringArgumentType.string())  // 权限节点
                                        .executes(context -> {
                                            String playerName = StringArgumentType.getString(context, "player");
                                            String permissionNode = StringArgumentType.getString(context, "permission");

                                            // 获取执行命令的玩家名称
                                            ServerCommandSource source = context.getSource();
                                            String executor = source.getName();

                                            // 检查是否为管理员（只有管理员能授予权限）
                                            if (!permissionManager.hasPermission(executor, "mingpixeltools.admin")) {
                                                Text message = Text.literal("你没有权限执行此操作！");
                                                LoggerUtil.logWarning("Player " + executor + " attempted to use /mp grant without proper permission.");
                                                return 0;
                                            }

                                            // 授予玩家权限
                                            permissionManager.grantPermission(playerName, permissionNode);
                                            source.sendFeedback(() -> Text.of("已成功授予 " + playerName + " 权限: " + permissionNode), false);
                                            LoggerUtil.logInfo("Player " + executor + " granted permission " + permissionNode + " to player " + playerName);
                                            return 1;  // 返回成功
                                        })
                                )
                        )
                )
                .build();
    }
}
